package com.grj.park.boot.config;

import cn.hutool.json.JSONUtil;
import com.grj.park.boot.domain.R;
import com.grj.park.boot.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Value("${my.array}")
    private static final String[] IGNORE_URLS = {"/login", "/register", "/doc.html", "/swagger-ui/index.html", "/swagger-resources/**", "/v3/api-docs", "/webjars/**"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        for (String ignoreUrl : IGNORE_URLS) {
            if (PATH_MATCHER.match(ignoreUrl, request.getServletPath())) {
                chain.doFilter(request, response);
                return;
            }
        }

        String authorizationHeader = request.getHeader("Authorization");
        response.setContentType("application/json; charset=UTF-8");

        if (authorizationHeader == null || authorizationHeader.isEmpty()) {
            R<Object> r = R.fail(401,"请先登录");
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return;
        }

        if (!authorizationHeader.startsWith("Bearer ")){
            R<Object> r = R.fail(401,"请先登录");
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return;
        }
        String username = null;
        String jwt = authorizationHeader.substring(7);

        try{
            username = jwtUtil.extractUsername(jwt);
        }catch (Exception e){
            response.setContentType("application/json; charset=UTF-8");
            R<Object> r = R.fail(401, "请重新登录");
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return;
        }
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            System.out.println(userDetails.getAuthorities());
            if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        Claims claims = jwtUtil.extractAllClaims(jwt);
        Object id = claims.get("id");
        request.setAttribute("id", id);
        chain.doFilter(request, response);
    }
}
